package com.helei.data.timer.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import cn.hutool.log.Log;
import com.helei.common.exception.WeApiException;
import com.helei.data.timer.TimerTaskRunner;
import com.helei.data.timer.service.TimerExeService;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * hutool方式的定时任务执行
 *
 * @author stylefeng
 * @date 2020/7/1 13:48
 */
@Service
public class HutoolTimerExeServiceImpl implements TimerExeService {

    private static final Log log = Log.get();
    private static String NOT_EXISTED = "您查询的该条记录不存在";
    private static String TIMER_NOT_EXISTED = "定时任务执行类不存在";
    private static String EXE_EMPTY_PARAM = "请检查定时器的id，定时器cron表达式，定时任务是否为空！";

    @Override
    public void startTimer(String taskId, String cron, String className) {

        if (ObjectUtil.hasEmpty(taskId, cron, className)) {
            throw new WeApiException(EXE_EMPTY_PARAM);
        }

        // 预加载类看是否存在此定时任务类
        try {
            Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new WeApiException(TIMER_NOT_EXISTED);
        }
        // 定义hutool的任务
        Task task = () -> {
            TimerTaskRunner timerTaskRunner = null;
            try {
                timerTaskRunner = (TimerTaskRunner) Class.forName(className).getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                log.error(">>> 任务执行异常：{}", e.getMessage());
            }
            timerTaskRunner.action();

        };
        try{
            // 开始执行任务
            CronUtil.schedule(taskId, cron, task);
        }catch (Exception e){
            log.error(e.getMessage());
            throw new WeApiException("该定时器已经运行中");
        }

       /* // 支持秒级别定时任务
        CronUtil.setMatchSecond(true);
        CronUtil.start();*/
    }

    @Override
    public void stopTimer(String taskId) {
        CronUtil.remove(taskId);
    }
}
